package org.example.myleet.learn.scriptEngine;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.PrintWriter;

public class JavaScriptEngineTest {
    public static void main(String[] args) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        try {
            //define a value in javascript
            engine.eval("n = 1728");
            Object result = engine.eval("n + 1");
            System.out.println(result.getClass().getSimpleName() + ": " + result);
            //bind a value in javascript engine context
            engine.put("k", result);
            result = engine.eval("k + 1");
            System.out.println(result.getClass().getSimpleName() + ": " + result);
            //redirect engine writer to System.out
            PrintWriter writer = new PrintWriter(System.out);
            engine.getContext().setWriter(writer);
            engine.eval("print('Hello, world!')");
            //define a function in javascript
            engine.eval("function greet(whom) { return 'Hello! ' + whom + ', welcome!' }");
            result = ((Invocable) engine).invokeFunction("greet", "Tommy");
            System.out.println(result.getClass().getSimpleName() + ": " + result);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
